﻿using System;
using System.Reflection;

namespace SimpleServiceBus.Utilities.ObjectBuilder
{
    public class DefaultObjectBuilderService : IObjectBuilderService
    {
        public DefaultObjectBuilderService():this(null)
        {
        }

        public DefaultObjectBuilderService(IObjectBuilder objectBuilder)
        {
            ObjectBuilder = objectBuilder ?? new DefaultObjectBuilder();
        }

        protected IObjectBuilder ObjectBuilder { get; private set; }

        #region IObjectBuilderService Members

        public object BuildObject(Type typeToBuild)
        {
            return ObjectBuilder.Build(typeToBuild);
        }

        public T BuildObject<T>() where T : class
        {
            return ObjectBuilder.Build<T>();
        }


        public ServiceType BuildService<ServiceType, DefaultImplementation>()
            where ServiceType : class
            where DefaultImplementation : class, ServiceType
        {
            var tryIoC = ObjectBuilder.TryBuild<ServiceType>();
            if (tryIoC == null)
                return ObjectBuilder.Build<DefaultImplementation>();
            return tryIoC;
        }

        public void RegisterSingleton<T>(T implementation)
        {
            ObjectBuilder.RegisterSingleton<T>(implementation);
        }

        #endregion
    }
}